<?php
// +----------------------------------------------------------------------
// | likeshop开源商城系统
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | gitee下载：https://gitee.com/likeshop_gitee
// | github下载：https://github.com/likeshop-github
// | 访问官网：https://www.likeshop.cn
// | 访问社区：https://home.likeshop.cn
// | 访问手册：http://doc.likeshop.cn
// | 微信公众号：likeshop技术社区
// | likeshop系列产品在gitee、github等公开渠道开源版本可免费商用，未经许可不能去除前后端官方版权标识
// |  likeshop系列产品收费版本务必购买商业授权，购买去版权授权后，方可去除前后端官方版权标识
// | 禁止对系统程序代码以任何目的，任何形式的再发布
// | likeshop团队版权所有并拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeshop.cn.team
// +----------------------------------------------------------------------
namespace app\admin\Logic;
use app\admin\model\Bottle;
use app\admin\Logic\BottleLogLogic;
use app\admin\model\BottleExetLog;
use app\admin\model\BottleLog;
use app\admin\model\User;
use app\common\server\UrlServer;
use think\Db;


class BottleLogic{
    public static function lists($get){
        $where = [];
        //类型搜索
        if (isset($get['type']) && $get['type']) {
            $where[] = ['status', '=' , $get['type']];
        }

        //启用状态搜索
        if (isset($get['use_status']) && $get['use_status']) {
            $where[] = ['use_status', '=' , $get['use_status']];
        }

        if (isset($get['code']) && $get['code']) {
            $where[] = ['code', '=' , $get['code']];
        }

        if (isset($get['shared_code']) && $get['shared_code']) {
            $where[] = ['shared_code', '=' , $get['shared_code']];
        }
        if (isset($get['remark']) && $get['remark']) {
            $where[] = ['remark', '=' , $get['remark']];
        }
        //启用日期
        if (isset($get['start_time']) && $get['start_time'] != '') {
            $where[] = ['use_date', '>=', strtotime($get['start_time'])];
        }
        if (isset($get['end_time']) && $get['end_time'] != '') {
            $where[] = ['use_date', '<=', strtotime($get['end_time'])];
        }
        $bottle = new Bottle();

        $bottle_count = $bottle
            ->where($where)
            ->count();

        $bottle_list = $bottle
            ->where($where)
            ->page($get['page'], $get['limit'])
            ->order('id desc')
            ->select();
        $bottle_list->append(['status_desc']);
        foreach ($bottle_list as $k=>$v){
            $bottle_list[$k]['site_name'] =  Db::name('bottle_site')->where(['id'=>$v['site_id']])->value('name');
        }
//        var_dump($bottle_list);
        return ['count' => $bottle_count, 'list' => $bottle_list];

    }

    //添加钢瓶
    public static function add($post){
        $bottle = new Bottle();
//        $bottleLog = new BottleLogLogic();
        Db::startTrans();
        //拼接数据
        $data = [
            'site_id'     => $post['site_id'],
            'code'        => $post['code'],
            'shared_code' => $post['shared_code'],
            'remark'      => $post['remark'],
            'status'      => 2,//钢瓶默认状态为空瓶
            'use_status'  => 1,//默认启用
            'createtime'  => date("Y-m-d H:i:s",time()),
        ];
        $logData = [
            'bottle_code' => $data['code'],
            'type'=>1,
            'admin_id'=>$post['admin_id'],
            'info'=>'新瓶入库到飞虹燃气',
        ];
//        $sta1 = $bottleLog::createBottleLog($logData);
        $bottleLog = new BottleLog();
        $bottleExetLog = new BottleExetLog();
        $logData['create_time'] =date("Y-m-d H:i:s",time());
        $sta1 = $bottleLog->insertGetId($logData);

        $stat2 = $bottle->allowField(true)->save($data);
        $bottle_exet_log = [
            'bottle_log_id'=>json_encode([$sta1]),
            'bootle_site_id'=>$post['site_id'],
            'create_time'=>date("Y-m-d H:i:s",time())
        ];
        $sta3 = $bottleExetLog->insert($bottle_exet_log);
        if($sta1==true && $stat2==true && $sta3==true){
            Db::commit();
            return true;
        }
        Db::rollback();
        return false;
    }

    public static function edit($post){
        $bottle = new Bottle();
        $res = $bottle->save($post,['id'=>$post['id']]);
        if($res==false){
            return false;
        }
        return true;
    }

    public static function first($id,$get_data = false){
        $user =  Bottle::get($id);
        return $user;
    }



    /*
     * 删除优惠券
     */
    public static function del($id){
        Db::startTrans();
        try{
            $coupon = new Coupon();
            $coupon->save(['del'=>1,'update_time'=>time()],['id'=>$id]);

            // 同步删除已领取未使用的用户的优惠券
            Db::name('coupon_list')->where([
                'status' => 0,
                'coupon_id' => $id,
                'del' => 0
            ])->update([
                'del' => 1,
                'update_time' => time()
            ]);

            Db::commit();
            return true;
        }catch(\Exception $e) {
            Db::rollback();
            return false;
        }
    }

    /*
     * 发放记录
     */
    public static function log($get){
        $where[] = ['cl.del','=',0];
        $where[] = ['coupon_id','=',$get['id']];
        if(isset($get['keyword']) && $get['keyword']){
            $where[] = ['nickname|mobile','like','%'.$get['keyword'].'%'];
        }

        $log_count = Db::name('coupon_list cl')
            ->join('user u','cl.user_id = u.id')
            ->where($where)
            ->count();

        $log_list =  Db::name('coupon_list cl')
            ->join('user u','cl.user_id = u.id')
            ->where($where)
            ->field('coupon_id,status,coupon_code,cl.create_time as create_time,cl.use_time,u.nickname,u.avatar,u.mobile,u.sex,u.sn,u.level,u.create_time as u_create_time')
            ->page($get['page'], $get['limit'])
            ->select();
        $coupon_list = Db::name('coupon')->where(['del'=>0])->column('name','id');
        $level_name = Db::name('user_level')->where(['del'=>0])->column('name','id');
        foreach ($log_list as &$item)
        {
            $item['use_time_desc'] = '-';
            $item['status_desc'] = '未使用';
            $item['create_time_desc'] = '';
            $item['sex_desc'] = '未知';
            if($item['use_time']){
                $item['use_time_desc'] = date('Y-m-d H:i:s',$item['use_time']);
            }
            $item['u_create_time'] = date('Y-m-d H:i:s',$item['u_create_time']);

            if ($item['status'] == 1) {
                $item['status_desc'] = '已使用';
            } else if($item['status'] == 2) {
                $item['status_desc'] = '已过期';
            }

            $item['avatar'] = UrlServer::getFileUrl($item['avatar']);
            $item['coupon_name'] = $coupon_list[$item['coupon_id']] ?? '';
            $item['create_time_desc'] = date('Y-m-d H:i:s',$item['create_time']);

            $item['level_name'] = $level_name[$item['level']] ?? '';
            switch ($item['sex']){
                case 1:
                    $item['sex_desc'] = '男';
                case 2:
                    $item['sex_desc'] = '女';

            }

        }
        return ['count'=>$log_count , 'lists'=>$log_list];
    }

    /*
     * 关闭优惠券
     */
    public static function close($id){
        $coupon = new Coupon();
        return $coupon->save(['status'=>0,'update_time'=>time()],['id'=>$id]);
    }


    public static function sendCoupon($post){
        $user_ids = $post['user_ids'];
        $coupon_ids = $post['coupon_ids'];
        $now = time();
        foreach ($coupon_ids as $coupon_id){
            foreach ($user_ids  as $user_id){
                $add_data = [
                    'user_id'       => $user_id,
                    'coupon_id'     => $coupon_id,
                    'status'        => 0,
                    'coupon_code'   => create_coupon_code(),
                    'create_time'   => $now,
                ];
                Db::name('coupon_list')->insert($add_data);

            }
        }
        return true;

    }




}